const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
// 创建集合云函数入口函数
exports.main = async (event, context) => {
  try {
    // 
    let num = parseInt(event.num)
    let randoms = Array()
    const students = await db.collection('student')
    let student = await students.field({ _id: true }).get()
    let count = await students.count()
    count = count['total']
    if (count < num) {
      return { success: false, msg: '设定人数超过班级总人数。' }
    }
    let random, data = Array()
    while (true) {
      random = Math.floor(Math.random() * count)
      if (!randoms.includes(random)) {
        if (randoms.push(random) == num) {
          break
        }
      }
    }
    for (let index = 0; index < randoms.length; index++) {
      let id = student.data[randoms[index]]._id
      data[index] = await students.doc(id).get()
      data[index] = data[index]['data']
    }
    return {
      success: true,
      data: {
        student: data
      }
    }
  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    console.log(e)
    return {
      success: false,
      data: e
    }
  }
}